import { defineStore } from 'pinia'
import Axios from 'axios'
import { getExpires, getToken, removeToken, getRefreshToken } from '@/utils/auth.js'
export const useUserStore = defineStore('user', () => {
  let token: string = ref(getToken() || '')
  let refreshToken: string = ref(getRefreshToken() || '')
  let expires_time: string = ref(getExpires() || '')
  function gwloginOut() {
    Axios.get('/gw/sso/logout').then(res => {
      loginOutHandler(res.data.data)
    })
  }
  function loginOutHandler(url: string) {
    localStorage.removeItem('x-ciot-uc')
    localStorage.removeItem('x-ciot-ucc')
    localStorage.removeItem('ciot_target')
    if (url) {
      window.location.href = url
      return
    }
    token = ''
    refreshToken = ''
    removeToken()
    window.location.href = import.meta.env.VITE_NODE_ENV === 'development' ? 'http://localhost:8888/passport/login' : location.origin + '/portal/#/?mk=dmc'
  }

  return {
    token,
    refreshToken,
    expires_time,

    gwloginOut,
    loginOutHandler
  }
})